package cn.com.lsy.product.lepao.controller;

import cn.com.lsy.product.lepao.common.Constant;
import cn.com.lsy.product.lepao.controller.base.BaseController;
import cn.com.lsy.product.lepao.model.entities.LpAdminTbl;
import cn.com.lsy.product.lepao.model.entities.LpRoleTbl;
import cn.com.lsy.product.lepao.model.mt.entities.AuthMenuDto;
import cn.com.lsy.product.lepao.request.LoginParam;
import cn.com.lsy.product.lepao.request.UpdatePwdParam;
import cn.com.lsy.product.lepao.response.LoginRet;
import cn.com.lsy.product.lepao.response.UserMenuListBaseRet;
import cn.com.lsy.product.lepao.response.UserMenuListRet;
import cn.com.lsy.product.lepao.response.base.ApiResponseEnum;
import cn.com.lsy.product.lepao.response.base.BaseRet;
import cn.com.lsy.product.lepao.service.IAdminService;
import cn.com.lsy.product.lepao.service.ILoggerService;
import cn.com.lsy.product.lepao.service.IRoleService;
import cn.com.lsy.product.lepao.service.ISessionService;
import cn.com.lsy.product.lepao.util.CommonFunctionUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Api(value = "登录接口", tags = "登录接口")
@RestController
@RequestMapping(value = "/lepao/console")
public class LoginController extends BaseController {

    private Logger log = Logger.getLogger(LoginController.class);
    Mapper mapper = new DozerBeanMapper();

    @Autowired
    IAdminService iAdminService;
    @Autowired
    ISessionService iSessionService;
    @Autowired
    IRoleService iRoleService;
    @Autowired
    ILoggerService iLoggerService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(notes = "登录", httpMethod = "POST", value = "登录")
    public BaseRet<LoginRet> login(
            @ApiParam(value = "请求参数", required = true) @Valid @RequestBody LoginParam param,
            BindingResult result, HttpServletRequest request) {

        BaseRet<LoginRet> ret = new BaseRet<LoginRet>();

        LoginRet loginRet = new LoginRet();

        try {

            checkParam(result);

            //查询用户信息
            List<LpAdminTbl> info = iAdminService.selectUserInfoByUsername(param.getUsername());

            if (info != null && info.size() > 0) {

                if (info.get(0).getPassword().equals(CommonFunctionUtil.encryptionPwd(param.getPassword()))) {

                    if (info.get(0).getStatus().equals(Constant.status.enable)) {

                        //生成token
                        String token = CommonFunctionUtil.createUuid();

                        iSessionService.createSession(info.get(0).getId(), Constant.roleType.console, token);

                        loginRet.setToken(token);
                        loginRet.setRoleId(info.get(0).getRoleId());
                        loginRet.setStoreId(JSONObject.parseArray(info.get(0).getStoreId(), Integer.class));

                        List<Integer> menuId = null;

                        if (info.get(0).getRoleId() > 0) {
                            LpRoleTbl roleInfo = iRoleService.selectRoleInfo(info.get(0).getRoleId());
                            //查询角色信息
                            if (StringUtils.isNotEmpty(roleInfo.getMenuJson())) {
                                menuId = JSONObject.parseArray(roleInfo.getMenuJson(), Integer.class);
                            }

                        }


                        //查询菜单列表
                        List<AuthMenuDto> menu = iRoleService.selectUserAuthMenuList(menuId);

                        List<UserMenuListBaseRet> userMenuListBase = new ArrayList<UserMenuListBaseRet>();

                        if (menu != null && menu.size() > 0) {

                            for (AuthMenuDto value : menu) {

                                UserMenuListBaseRet userMenuListBaseRet = new UserMenuListBaseRet();
                                userMenuListBaseRet.setIcon(value.getIcon());
                                userMenuListBaseRet.setName(value.getName());

                                if (StringUtils.isNotEmpty(value.getChildName())) {

                                    String[] name = value.getChildName().split(",");
                                    String[] url = value.getChildUrl().split(",");

                                    List<UserMenuListRet> userMenuList = new ArrayList<UserMenuListRet>();

                                    for (int i = 0; i < name.length; i++) {
                                        UserMenuListRet userMenuListRet = new UserMenuListRet();
                                        userMenuListRet.setName(name[i]);
                                        userMenuListRet.setUrl(url[i]);
                                        userMenuList.add(userMenuListRet);
                                    }

                                    userMenuListBaseRet.setMenuList(userMenuList);
                                }

                                userMenuListBase.add(userMenuListBaseRet);

                            }

                        }

                        loginRet.setMenuList(userMenuListBase);

                        //记录日志
                        iLoggerService.insert(info.get(0).getId(), Constant.logType.login, "登录", CommonFunctionUtil.getClientIp(request));

                        ret.setData(loginRet);
                        ret.setMsg("登录成功");
                        ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);


                    } else {

                        ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                        ret.setMsg("账号已被禁用");
                    }

                } else {

                    ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                    ret.setMsg("密码不正确");
                }

            } else {

                ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                ret.setMsg("用户不存在");
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/doAuth/updatePwd", method = RequestMethod.POST)
    @ApiOperation(notes = "修改密码", httpMethod = "POST", value = "修改密码")
    public BaseRet<String> updatePwd(
            @ApiParam(value = "请求参数", required = true) @Valid @RequestBody UpdatePwdParam param,
            BindingResult result) {

        BaseRet<String> ret = new BaseRet<String>();

        try {

            checkParam(result);

            int userId = getUserId();

            LpAdminTbl info = iAdminService.selectUserInfoById(userId);

            if (info.getPassword().equals(CommonFunctionUtil.encryptionPwd(param.getOldPwd()))) {

                //修改密码
                LpAdminTbl lpAdminTbl = new LpAdminTbl();
                lpAdminTbl.setId(userId);
                lpAdminTbl.setPassword(CommonFunctionUtil.encryptionPwd(param.getNewPwd()));

                if (iAdminService.updateInfo(lpAdminTbl)) {

                    ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
                    ret.setMsg("修改成功");

                } else {

                    ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                    ret.setMsg("修改失败");
                }

            } else {

                ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                ret.setMsg("旧密码有误");
            }


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }
}
